package com.iaiai.browser.activity.widget;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebIconDatabase;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import com.iaiai.browser.activity.R;
import com.iaiai.browser.core.util.Message;

/**
 * 
 * <p>
 * Title: IndexController.java
 * </p>
 * <p>
 * E-Mail: 176291935@qq.com
 * </p>
 * <p>
 * QQ: 176291935
 * </p>
 * <p>
 * Http: iaiai.iteye.com
 * </p>
 * <p>
 * Create time: 2011-11-2
 * </p>
 * 
 * @author 丸子
 * @version 0.0.1
 */
public class BodyManager {

	public interface Handler {
		void loading(int index); // 加载

		void unLoading(int index); // 取消加载

		void onIcon(int index, Bitmap icon); // icon

		void onTitle(int index, String title); // 标题

		void open(String url); // 打开
		
		void showIndex();	//显示首页
	}

	private Context context;

	private List<WebView> webViewList = new ArrayList<WebView>();

	private LinearLayout webViewLayout; // 控件体布局

	private LinearLayout indexLabelLayout; // 首页体布局

	private Handler handler; // 事件

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	/**
	 * 创建目录
	 * @param path
	 * @return
	 */
	private static String getDirs(String path) {
		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return path;
	}

	public BodyManager(Context context) {
		this.context = context;
		
		WebIconDatabase.getInstance().open(getDirs(context.getFilesDir().toString()+"/icons/"));	//创建用于保存icon目录

		init();
	}

	private Activity getActivity() {
		return (Activity) context;
	}

	private void init() {
		webViewLayout = (LinearLayout) getActivity().findViewById(R.id.webViewLayout);
		indexLabelLayout = (LinearLayout) getActivity().findViewById(R.id.indexLabelLayout);
	}

	/**
	 * 添加WebView
	 * 
	 * @param url
	 */
	public void addWebView(String url) {
		final int index = webViewList.size()+1;	//当前第几个
		
		final WebView webView = new WebView(context);
		webView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
				LinearLayout.LayoutParams.FILL_PARENT));
		webView.getSettings().setDefaultTextEncodingName("UTF-8");
		webView.getSettings().setJavaScriptEnabled(true); // 允许java跟javascript相互调用
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setBuiltInZoomControls(true);
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				Message.showToast(getActivity(), "出错啦:" + errorCode);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				handler.unLoading(index);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				handler.loading(index);
			}
		});
		webView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int progress) {
				getActivity().setProgress(progress * 1000);
			}

			@Override
			public void onReceivedTitle(WebView view, String title) { // 获得标题
				handler.open(view.getUrl());
				for (int i = 0; i < webViewLayout.getChildCount(); i++) {
					if (webViewLayout.getChildAt(i) == webView) {
						handler.onTitle(i + 1, title);
						break;
					}
				}
			}

			@Override
			public void onReceivedIcon(WebView view, Bitmap icon) {
				for (int i = 0; i < webViewLayout.getChildCount(); i++) {
					if (webViewLayout.getChildAt(i) == webView) {
						handler.onIcon(i + 1, icon);
						break;
					}
				}
			}
		});
		webView.loadUrl(url);

		webViewLayout.addView(webView);
		webViewList.add(webView);

		show(webViewList.size()); // 显示哪个
	}

	/**
	 * 显示哪个WebView
	 * 
	 * @param index
	 *            从1开始
	 */
	public void show(int index) {
		indexLabelLayout.setVisibility(View.GONE);
		webViewLayout.setVisibility(View.VISIBLE);

		for (int i = 0; i < webViewList.size(); i++) {
			webViewList.get(i).setVisibility(i + 1 == index ? View.VISIBLE : View.GONE);
		}
	}
	
	/**
	 * 显示home页
	 */
	public void showHome() {
		indexLabelLayout.setVisibility(View.VISIBLE);
		webViewLayout.setVisibility(View.GONE);
	}

	/**
	 * 删除
	 * 
	 * @param index
	 *            第几个，从1开始
	 */
	public void remove(int index) {
		webViewLayout.removeViewAt(index - 1);
		webViewList.remove(index - 1);

		// 如果数据不大于0，则显示首页
		if (webViewLayout.getChildCount() <= 0) {
			indexLabelLayout.setVisibility(View.VISIBLE);
			webViewLayout.setVisibility(View.GONE);

			webViewList = new ArrayList<WebView>();
			
			handler.showIndex();	//显示首页
		}
	}

	/**
	 * 显示首页
	 */
	public void showIndex() {
		indexLabelLayout.setVisibility(View.VISIBLE);
		webViewLayout.setVisibility(View.GONE);
	}

	/**
	 * 获得当前选择的url
	 * 
	 * @return
	 */
	public String getSelUrl() {
		String url = null;
		for (int i = 0; i < webViewList.size(); i++) {
			if (webViewList.get(i).getVisibility() == View.VISIBLE) {
				url = webViewList.get(i).getOriginalUrl();
				break;
			}
		}
		return url;
	}
	
	/**
	 * 获得截图
	 * @return
	 */
	public Bitmap getSelScreen(){
		Bitmap bmp = null;
		try{
		for (int i = 0; i < webViewList.size(); i++) {
			if (webViewList.get(i).getVisibility() == View.VISIBLE) {
				Picture picture = webViewList.get(i).capturePicture();
				bmp = Bitmap.createBitmap(picture.getWidth(),picture.getHeight(), Bitmap.Config.ARGB_8888);
				Canvas c = new Canvas(bmp);
				picture.draw(c);
				webViewList.get(i).draw(c);
				break;
			}
		}
		}catch(Exception e){
			Log.i("BodyManager","截图时出错:"+e.getMessage());
		}
		return bmp;
	}

	/**
	 * 刷新
	 */
	public void ref() {
		for (int i = 0; i < webViewList.size(); i++) {
			if (webViewList.get(i).getVisibility() == View.VISIBLE) {
				webViewList.get(i).reload();
				break;
			}
		}
	}

	/**
	 * 向前
	 */
	public void goForward() {
		for (int i = 0; i < webViewList.size(); i++) {
			if (webViewList.get(i).getVisibility() == View.VISIBLE) {
				webViewList.get(i).goForward();
				break;
			}
		}
	}

	/**
	 * 向后
	 */
	public void goBack() {
		for (int i = 0; i < webViewList.size(); i++) {
			if (webViewList.get(i).getVisibility() == View.VISIBLE) {
				webViewList.get(i).goBack();
				break;
			}
		}
	}

}
